var request = require("request");
var cheerio = require("cheerio");
var fs = require("fs");
let url = "https://www.qingmo.net/yuanzhuopai/page/";

for (let index = 1; index < 11; index++) {
  console.log("开始读取第" + index + "页");
  fs.exists("./yzp", function (exists) {
    if (!exists) {
      fs.mkdir("./yzp", 0777, function (err) {
        if (err) {
          throw err;
        } else {
          videocrawler(url+index, function (err, videoList) {
              if (err) {
                return console.log(err);
              }
            });
        }
      });
    }else{
        videocrawler(url+index, function (err, videoList) {
            if (err) {
              return console.log(err);
            }
          });
    }
  });
}
var downLoadMp3 = function (dir, name, filePath) {
  request(dir)
    .pipe(fs.createWriteStream(filePath + name + ".mp3"))
    .on("close", function () {
        console.log('saved' + name)
    });
};

function videocrawler(url, callback) {
  request(url, function (err, res) {
    if (err) {
      callback(err);
    }
    var $ = cheerio.load(res.body.toString()); 
    var videoList = [];
    $(".postone").each(function () {
      let name = $(this).find("h2 a").html();
      let url = $(this).find(".posttow audio").attr("src");
      downLoadMp3(url, name, "./yzp/");
    });
    callback(null, videoList);
  });
}
